<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="会员ID" prop="membershipId">
        <el-input
          v-model="queryParams.membershipId"
          placeholder="请输入会员ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会员卡号" prop="membershipCardNumber">
        <el-input
          v-model="queryParams.membershipCardNumber"
          placeholder="请输入会员卡号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="患者id" prop="patientId">
        <el-input
          v-model="queryParams.patientId"
          placeholder="请输入患者id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开卡时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeMembershipOpeningTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="会员状态" prop="membershipStatus">
        <el-select v-model="queryParams.membershipStatus" placeholder="请选择会员状态" clearable>
          <el-option
            v-for="dict in sys_status_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['membership:membership:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['membership:membership:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['membership:membership:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['membership:membership:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="membershipList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="会员ID" align="center" prop="membershipId" />
      <el-table-column label="会员卡号" align="center" prop="membershipCardNumber" />
      <el-table-column label="会员类型" align="center" prop="membershipType" />
      <el-table-column label="姓名" align="center"  prop="patient.realName">
         <template #default="scope" ><a @click="test(scope.row.patient.patientId )">{{ scope.row.patient.realName }}</a></template>
      </el-table-column>

      <el-table-column label="手机号" align="center" prop="patient.phoneNumber" />

      <el-table-column label="会员等级" align="center" prop="membershipLevel.levelName" />
      <el-table-column label="累计消费(元)" align="center" prop="totalConsumption" />
      <el-table-column label="储值余额" align="center" prop="valueStorage.storageBalance" />
      <el-table-column label="开卡时间" align="center" prop="membershipOpeningTime" width="180">
      <template #default="scope">
          <span>{{ parseTime(scope.row.membershipOpeningTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会员状态" align="center" prop="membershipStatus">
        <template #default="scope">
          <dict-tag :options="sys_status_type" :value="scope.row.membershipStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['membership:membership:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['membership:membership:remove']">删除</el-button>
          <el-button style="margin-right: 16px" @click="handleShow(scope.row)" v-hasPermi="['membership:membership:query']">充值/退款记录</el-button>
          <el-button type="primary" size="small" @click="chongzhitanchuang(scope.row)">充值</el-button>
          <el-button type="danger" size="small" @click="tuikuantanchuang(scope.row)">退款</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
<!--从会员卡充值/退款记录-->
    <el-dialog v-model="dialogVisible" title="变更记录" width="800">
      <el-table :data="gridData">
        <el-table type="selection" width="55" align="center" />
        <el-table-column label="会员卡号" align="center" prop="membershipVardNumber" />
        <el-table-column label="会员姓名" align="center" prop="patient.realName" />
        <el-table-column label="变动时间" align="center" prop="levelChangeTime" width="160px"/>
        <el-table-column label="变更类型" align="center" prop="levelChangeType" />
        <el-table-column label="余额" align="center" prop="storageBalance"/>
        <el-table-column label="累计充值" align="center" prop="cumulativeRecharge"/>
        <el-table-column label="扣款金额" align="center" prop="jianshaoJine"/>
      </el-table>
    </el-dialog>



    <!-- 添加或修改会员列表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="membershipRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="会员卡号" prop="membershipCardNumber">
          <el-input v-model="form.membershipCardNumber" placeholder="请输入会员卡号" />
        </el-form-item>
        <el-form-item label="患者id" prop="patientId">
          <el-input v-model="form.patientId" placeholder="请输入患者id" />
        </el-form-item>
        <el-form-item label="累计消费(元)" prop="totalConsumption">
          <el-input v-model="form.totalConsumption" placeholder="请输入累计消费(元)" />
        </el-form-item>
        <el-form-item label="开卡时间" prop="membershipOpeningTime">
          <el-date-picker clearable
            v-model="form.membershipOpeningTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开卡时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="会员状态" prop="membershipStatus">
          <el-select v-model="form.membershipStatus" placeholder="请选择会员状态">
            <el-option
              v-for="dict in sys_status_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
<!--充值弹窗-->
    <el-dialog :title="title1" v-model="open1" width="500px" append-to-body>
      <el-form ref="membershipRef" :model="formcz" :rules="rules" label-width="80px">
        <el-form-item label="患者id" prop="patientId">
          <el-input v-model="formcz.patientId" placeholder="请输入会员id" />
        </el-form-item>
        <el-form-item label="增加金额" prop="zengjiajine">
          <el-input v-model="formcz.zengjiaJine" placeholder="请输入充值金额" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="abd">确 定</el-button>
          <el-button @click="quxiao">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--退款弹窗-->
    <el-dialog :title="title2" v-model="open2" width="500px" append-to-body>
      <el-form ref="membershipRef" :model="formcz" :rules="rules" label-width="80px">
        <el-form-item label="患者id" prop="patientId">
          <el-input v-model="formcz.patientId" placeholder="请输入会员id" />
        </el-form-item>
        <el-form-item label="退款金额" prop="tuikuanJine">
          <el-input v-model="formcz.jianshaoJine" placeholder="请输入退款金额" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="jbd">确 定</el-button>
          <el-button @click="quxiao">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Membership">
import router from "@/router/index.js";

const test = (patientId) =>{
  let temp = new Date();
  let tt =  Math.random();
  router.push({ path: '/member', query: { patientId:patientId, tt:temp} });
}
const dataa={
  levelChangeTime:null,
  levelChangeType:null,
  patient:{
    realName:null
  },
  caozuoyuan:null,
}
const gridData=ref([]);
const dialogVisible = ref(false);

import {
  listMembership,
  getMembership,
  delMembership,
  addMembership,
  updateMembership, listvipchangelog, chongzhidialog, tuikuandialog
} from "@/api/membership/membership";

const { proxy } = getCurrentInstance();
const { sys_status_type } = proxy.useDict('sys_status_type');

const membershipList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeMembershipOpeningTime = ref([]);
const title1 = ref("");
const title2 = ref();
const open1 = ref(false);
const open2 = ref(false);
const data = reactive({
  form: {},
  formcz: {
    patientId:null,
    zengjiaJine:null,
    jianshaoJine:null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    membershipId: null,
    membershipCardNumber: null,
    membershipType: null,
    patientId: null,
    membershipOpeningTime: null,
    membershipStatus: null,
  },
  rules: {
    membershipCardNumber: [
      { required: true, message: "会员卡号不能为空", trigger: "blur" }
    ],
    membershipType: [
      { required: true, message: "会员类型不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules, formcz } = toRefs(data);

/** 查询会员列表列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeMembershipOpeningTime && '' != daterangeMembershipOpeningTime) {
    queryParams.value.params["beginMembershipOpeningTime"] = daterangeMembershipOpeningTime.value[0];
    queryParams.value.params["endMembershipOpeningTime"] = daterangeMembershipOpeningTime.value[1];
  }
  listMembership(queryParams.value).then(response => {
    membershipList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// /** 查询会员变更记录 */
function handleShow(row) {
  const membershipId = row.membershipId;
  console.log()
  console.log(membershipId)
  dialogVisible.value = true;
  listvipchangelog(membershipId).then(respponse => {
    // gridData.value[0].levelChangeTime=respponse.data.levelChangeTime;
    // gridData.value[0].levelChangeType=respponse.data.levelChangeType;
    // gridData.value[0].patient.realName=respponse.data.patient.realName;
    // gridData.value[0].caozuoyuan=respponse.data.caozuoyuan;
    gridData.value=respponse.data;
    console.log(gridData);
  })
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    membershipId: null,
    membershipCardNumber: null,
    membershipType: null,
    patientId: null,
    totalConsumption: null,
    membershipOpeningTime: null,
    membershipStatus: null,
    ext1: null,
    ext2: null,
    ext3: null
  };
  proxy.resetForm("membershipRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeMembershipOpeningTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.membershipId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加会员列表";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _membershipId = row.membershipId || ids.value
  getMembership(_membershipId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改会员列表";
  });
}

// 充值弹窗
function chongzhitanchuang(row){
  open1.value = true;

}
// 确认充钱
function abd(){
  chongzhidialog(formcz.value).then(response => {
    proxy.$modal.msgSuccess("充值成功");
    open1.value = false;
    getList();
  });
}
// 退款弹窗
function tuikuantanchuang(row){
  open2.value = true;

}
// 确认退款
function jbd(){
  tuikuandialog(formcz.value).then(response => {
    proxy.$modal.msgSuccess("退款成功");
    open2.value = false;
    getList();
  });
}
// 取消充钱
function quxiao(){
  open1.value = false;
  open2.value = false;
}





/** 提交按钮 */
function submitForm() {
  proxy.$refs["membershipRef"].validate(valid => {
    if (valid) {
      if (form.value.membershipId != null) {
        updateMembership(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMembership(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _membershipIds = row.membershipId || ids.value;
  proxy.$modal.confirm('是否确认删除会员列表编号为"' + _membershipIds + '"的数据项？').then(function() {
    return delMembership(_membershipIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('membership/membership/export', {
    ...queryParams.value
  }, `membership_${new Date().getTime()}.xlsx`)
}

getList();
</script>
